package com.md.application.service;

import com.google.common.collect.Lists;
import com.md.api.UsersApi;
import com.md.application.assembler.UsersAssembler;
import com.md.base.request.IdRequest;
import com.md.domain.model.po.UsersPO;
import com.md.domain.service.AuthenticationDomainServices;
import com.md.domain.service.ConfigDomainServices;
import com.md.model.page.PageResponse;
import com.md.model.system.CommonResult;
import com.md.request.LinkRoleRequest;
import com.md.request.QueryUsersPageRequest;
import com.md.request.RegisterUsersRequest;
import com.md.response.UsersDetailResponse;
import com.md.response.UsersResponse;
import com.md.util.ObjectUtil;
import com.md.value.GlobalConfigTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author 刘骄阳
 * 2024-12-15 1:46
 */
@Service
@RequiredArgsConstructor
public class UsersApplication implements UsersApi {
  private final AuthenticationDomainServices authenticationDomainServices;
  private final ConfigDomainServices configDomainServices;

  @Override
  public CommonResult<UsersResponse> register(final RegisterUsersRequest request) {
    checkUserFormat(request);
    UsersPO users = UsersAssembler.buildRegisterUsersPO(request);
    String roleId = configDomainServices.selectConfig(GlobalConfigTypeEnum.DEFAULT_ROLE);
    if (ObjectUtil.isEmpty(users.getAvatar())) {
      users.setAvatar(configDomainServices.selectConfig(GlobalConfigTypeEnum.DEFAULT_AVATAR));
    }
    List<Long> roleIdList = Optional.ofNullable(roleId).map(Long::parseLong).map(Lists::newArrayList)
      .orElse(Lists.newArrayList());
    authenticationDomainServices.createUser(users, roleIdList);
    return CommonResult.success(UsersAssembler.buildUsers2Response(users));
  }

  @Override
  public CommonResult<Void> checkUserFormat(final RegisterUsersRequest request) {
    UsersAssembler.checkRegisterUserRequest(request);
    authenticationDomainServices.checkUserFormat(request.getPhone(), request.getName());
    return CommonResult.success();
  }

  @Override
  public CommonResult<Void> linkRole(final LinkRoleRequest request) {
    authenticationDomainServices.linkUsersRole(request.getUserId(), request.getRoleIdList());
    return CommonResult.success();
  }

  @Override
  public CommonResult<PageResponse<UsersResponse>> list(final QueryUsersPageRequest request) {
    return CommonResult.success(authenticationDomainServices.list(UsersAssembler.buildQueryUsersBO(request)));
  }

  @Override
  public CommonResult<UsersDetailResponse> detail(final IdRequest request) {
    return CommonResult.success(authenticationDomainServices.usersDetail(request.getId()));
  }
}
